package com.wnxy.pms.member.core.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wnxy.common.jwt.JwtTemplate;
import com.wnxy.pms.member.core.constant.RedisConstant;
import com.wnxy.pms.member.core.constant.UserConstant;
import com.wnxy.pms.member.core.dto.UserDto;
import com.wnxy.pms.member.core.entity.User;
import com.wnxy.pms.member.core.exception.Asserts;
import com.wnxy.pms.member.core.mapper.UserMapper;
import com.wnxy.pms.member.core.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 会员用户表 服务实现类
 * </p>
 *
 * @author Jet
 * @since 2022-06-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtTemplate jwtTemplate;


    @Override
    public String login(UserDto userDto) {
        //1. 根据手机号查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_mobile",userDto.getMobile());
        User user = getOne(wrapper);

        //2. 判断
        //2.1 手机号是否存在
        if (Objects.isNull(user)) {
            //throw new BusinessException("账号或密码错误！");
            Asserts.failed("账号或密码错误!");
        }
        //2.2 密码校验
        // 数据库密码(加密的)   与   用户输入的密码
        if (!BCrypt.checkpw(userDto.getPassword(),user.getLoginPassword())) {
            Asserts.failed("账号或密码错误!");
        }
        //3. 校验通过，生成token
        // 载荷：token中存放的数据
        Map<String,Object> playload = new HashMap<>();
        playload.put(UserConstant.USER_ID,user.getUserId());
        // 生成token
        String token = jwtTemplate.createToken(playload);

        //4. 把token存储到redis中
        redisTemplate.opsForValue().set(
                RedisConstant.USER_TOKEN+user.getUserId(),token, Duration.ofMinutes(30));

        //5. 返回token
        return token;
    }

    public static void main(String[] args) {
        // 加密
        String hashpw = BCrypt.hashpw("123456");
        System.out.println("hashpw = " + hashpw);

        // 校验
        boolean flag = BCrypt.checkpw("123456", "$2a$10$u1lgi8eg/ggWOAZ89oUIOux8lczHBLA9a/Foie8IWKZPKR6CRd4uq");
        System.out.println("校验密码 = " + flag);
    }
}
